import address from '~/data/address';

const SERVER = process.env.NODE_ENV == 'development' ? 'https://geth.link/api' : '/api'

export const getNewMnemonic = async () => {
  return await (await fetch(SERVER, {method:'GET'})).json()
}

export const getKeystore = async (
  mnemonic: string, password: string, chain: string,
  start_index: string, validator_number: string) => {
  return await (
    await fetch(SERVER, {
      method: 'POST',
      body: JSON.stringify({
        mnemonic,
        password,
        chain,
        validator_start_index: start_index,
        num_validators: validator_number
      })
    })
  ).json()
}

export const recentDeposit = async (contractAddress: string) => {
  try {
    const res = await fetch("https://graphql.bitquery.io/", {
      "headers": {
        "accept": "application/json",
        "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
        "content-type": "application/json",
        "sec-ch-ua": "\" Not A;Brand\";v=\"99\", \"Chromium\";v=\"99\", \"Microsoft Edge\";v=\"99\"",
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": "\"macOS\"",
        "sec-fetch-dest": "empty",
        "sec-fetch-mode": "cors",
        "sec-fetch-site": "same-origin",
        "x-api-key": "BQYvhnv04csZHaprIBZNwtpRiDIwEIW9"
      },
      "referrer": "https://graphql.bitquery.io/ide",
      "referrerPolicy": "strict-origin-when-cross-origin",
      "body": "{\"query\":\"query ($network: EthereumNetwork!, $address: String!, $limit: Int!, $offset: Int!, $from: ISO8601DateTime, $till: ISO8601DateTime) {\\n  ethereum(network: $network) {\\n    smartContractCalls(\\n      options: {desc: \\\"block.timestamp.time\\\", limit: $limit, offset: $offset}\\n      date: {since: $from, till: $till}\\n      smartContractAddress: {is: $address}\\n      smartContractMethod: {is: \\\"deposit\\\"}\\n    ) {\\n      block {\\n        timestamp {\\n          time(format: \\\"%Y-%m-%d %H:%M:%S\\\")\\n        }\\n        height\\n      }\\n      smartContractMethod {\\n        name\\n        signatureHash\\n      }\\n      address: caller {\\n        address\\n        annotation\\n      }\\n      transaction {\\n        hash\\n      }\\n      gasValue\\n      external\\n    }\\n  }\\n}\\n\",\"variables\":\"{\\n  \\\"limit\\\": 1,\\n  \\\"offset\\\": 0,\\n  \\\"network\\\": \\\"goerli\\\",\\n  \\\"address\\\": \\\""+ contractAddress +"\\\",\\n  \\\"from\\\": \\\"2022-02-13\\\",\\n  \\\"till\\\": \\\"2022-03-14T23:59:59\\\",\\n  \\\"dateFormat\\\": \\\"%Y-%m-%d\\\"\\n}\"}",
      "method": "POST",
      "mode": "cors",
    });
    return (await res.json())['data']['ethereum']['smartContractCalls'][0]
  }
  catch (err) {
    return undefined
  }
}

export const getLatestTxn = async () => {
  const chainNames = Object.keys(address)
  const contractAddrs = Object.values(address)
  let latestTxn = await Promise.all(contractAddrs.map(addr => recentDeposit(addr)))
  latestTxn = latestTxn.map((item, i) => ({
    address: contractAddrs[i],
    name: chainNames[i],
    latestTxn: latestTxn[i]
  }))
  latestTxn = latestTxn.filter(item => item.latestTxn != undefined)
  latestTxn.sort((b, a) => a.latestTxn.block.height - b.latestTxn.block.height)
  latestTxn = latestTxn[0]
  return latestTxn
}

export const depositHistory = async (addr: string) => {
  const res = await fetch("https://graphql.bitquery.io/", {
    "headers": {
      "accept": "application/json",
      "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
      "content-type": "application/json",
      "sec-ch-ua": "\" Not A;Brand\";v=\"99\", \"Chromium\";v=\"99\", \"Microsoft Edge\";v=\"99\"",
      "sec-ch-ua-mobile": "?0",
      "sec-ch-ua-platform": "\"macOS\"",
      "sec-fetch-dest": "empty",
      "sec-fetch-mode": "cors",
      "sec-fetch-site": "same-origin",
      "x-api-key": "BQYvhnv04csZHaprIBZNwtpRiDIwEIW9"
    },
    "referrer": "https://graphql.bitquery.io/ide",
    "referrerPolicy": "strict-origin-when-cross-origin",
    "body": "{\"query\":\"query ($network: EthereumNetwork!, $address: String!, $limit: Int!, $offset: Int!, $from: ISO8601DateTime, $till: ISO8601DateTime) {\\n  ethereum(network: $network) {\\n    smartContractCalls(\\n      options: {desc: \\\"block.timestamp.time\\\", limit: $limit, offset: $offset}\\n      date: {since: $from, till: $till}\\n      smartContractAddress: {is: $address}\\n      smartContractMethod: {is: \\\"deposit\\\"}\\n    ) {\\n      block {\\n        timestamp {\\n          time(format: \\\"%Y-%m-%d %H:%M:%S\\\")\\n        }\\n        height\\n      }\\n      smartContractMethod {\\n        name\\n        signatureHash\\n      }\\n      address: caller {\\n        address\\n        annotation\\n      }\\n      transaction {\\n        hash\\n      }\\n      gasValue\\n      external\\n    }\\n  }\\n}\\n\",\"variables\":\"{\\n  \\\"limit\\\": 10,\\n  \\\"offset\\\": 0,\\n  \\\"network\\\": \\\"goerli\\\",\\n  \\\"address\\\": \\\""+addr+"\\\",\\n  \\\"from\\\": \\\"2020-01-01\\\",\\n  \\\"till\\\": \\\"2022-03-16T23:59:59\\\",\\n  \\\"dateFormat\\\": \\\"%Y-%m-%d\\\"\\n}\"}",
    "method": "POST",
    "mode": "cors",
  });
  const data = (await res.json()).data.ethereum.smartContractCalls
  return data;
}